<template>
  <el-form
    size="large"
    :rules="Rules"
    ref="codeForm"
    :model="formData"
    label-width="100px"
  >
    <el-form-item prop="codeText" label="代码名称">
      <el-input clearable placeholder="请输入代码名称" v-model="formData.codeText"></el-input>
    </el-form-item>
    <el-form-item prop="codeValue" label="代码值">
      <el-input clearable placeholder="请输入代码值" v-model="formData.codeValue"></el-input>
    </el-form-item>
    <el-form-item prop="type" label="代码类型">
      <el-radio-group v-model="formData.type" @change="changeType">
        <el-radio-button v-for="item in codeType" :key="item" :label="item.value">
          {{ item.label }}
        </el-radio-button>
      </el-radio-group>
    </el-form-item>
    <el-form-item prop="showOrder" label="代码排序">
      <el-input-number v-model="formData.showOrder" :step="5" :min="0"></el-input-number>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm(codeForm)">保存</el-button>
      <el-button type="info" @click="handleClose">关闭</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { getArrayText } from '@/utils/common'
import { CodeBeanData, Rules } from '@/model/system/code/CodeConstants'
import { saveCode, loadCodeById, getMaxIndex } from '@/api/system/code/CodeManager'

const codeForm = ref()
const props = defineProps({ fid: String, id: String })
const emit = defineEmits(['close-dialog', 'reload-data'])
const formData = ref({ ...CodeBeanData, fid: props.fid })
const codeType = [{ value: 1, label: '文件夹' }, { value: 2, label: '代码值' }]

const handleClose = () => {
  emit('close-dialog')
}

const submitForm = async (codeForm) => {
  if (!codeForm) return
  codeForm.validate(valid => {
    if (valid) {
      saveCode(formData.value).then(() => {
        ElMessage({
          message: '保存成功！',
          type: 'success',
          duration: 800
        })
        emit('reload-data')
        emit('close-dialog')
      }).catch(error => {
        ElMessage.error(error.message || '保存失败！')
      })
    }
  })
}

const changeType = (value) => {
  formData.value.typeText = getArrayText(value, codeType)
}

onMounted(() => {
  if (props.id) {
    loadCodeById(props.id).then(data => {
      formData.value = { ...data }
    })
  } else {
    formData.value.type = 1
    formData.value.typeText = getArrayText(formData.value.type, codeType)
    getMaxIndex(props.fid).then(data => {
      formData.value.showOrder = data + 5
    })
  }
})

</script>
